package com.yujie.filter;

import com.yujie.exception.BusinessException;
import com.yujie.exception.EmployeeErrorCodeEnum;
import com.yujie.util.R;
import com.yujie.util.StackTraceInfo;
import com.yujie.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class ControllerExceptionFilter extends OncePerRequestFilter {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            R r = new R();
            if (e.getCause() instanceof BusinessException) {
                BusinessException b = (BusinessException) e.getCause();
                EmployeeErrorCodeEnum errorCodeEnum = b.getErrorCodeEnum();
                String message = e.getCause().getMessage();
                if (errorCodeEnum.getCode().contains("B")) {
                    logger.error(message, b);
                } else {
                    logger.info(message, b);
                }
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                r.setCode(errorCodeEnum.getCode());
                r.setMessage(message);
                String stackTraceInfo = new StackTraceInfo().stackTraceInfo(e);
                r.setData(e.getCause().toString() + stackTraceInfo);
            } else {
                logger.error(e.getMessage(), e);
                r.setCode("B0001");
                r.setMessage("系统错误");
                String stackTraceInfo = new StackTraceInfo().stackTraceInfo(e);
                r.setData(e.getMessage()+stackTraceInfo);
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
            WebUtils.renderString(response, r);
        }
    }
}